package org.xshop.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.xshop.core.ExpressmanHelper;
import org.xshop.core.JPush2Helper;
import org.xshop.model.TExpressman;
import org.xshop.model.TMember;
import org.xshop.service.ITExpressmanService;

import com.alibaba.fastjson.JSON;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import top.ibase4j.core.Constants.MSGCHKTYPE;
import top.ibase4j.core.base.AppBaseController;
import top.ibase4j.core.exception.IllegalParameterException;
import top.ibase4j.core.exception.LoginException;
import top.ibase4j.core.support.Token;
import top.ibase4j.core.util.CacheUtil;
import top.ibase4j.core.util.ExceptionUtil;
import top.ibase4j.core.util.IDCardUtil;
import top.ibase4j.core.util.InstanceUtil;
import top.ibase4j.core.util.SecurityUtil;
import top.ibase4j.core.util.WebUtil;

/**
 * Created by BaiJiFeiLong@gmail.com at 2018/4/3 11:54
 */
@Controller
@RequestMapping("/app/expressman/")
@Api(tags = "Expressman", description = "骑手APP")
public class TExpressmanController extends AppBaseController<TExpressman, ITExpressmanService> {
    @Autowired
    private JPush2Helper jpushHelper;

    @PostMapping("reginit.api")
    @ApiOperation(value = "骑手注册", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ModelMap> reginit(
        @RequestHeader("UUID") @ApiParam(value = "客户端生成的唯一ID", required = true) String uuid,
        @RequestParam @ApiParam(value = "手机号", required = true) String account,
        @RequestParam @ApiParam(value = "密码", required = true) String password,
        @RequestParam @ApiParam(value = "手机验证码", required = true) String authCode,
        @RequestParam @ApiParam(value = "姓名", required = true) String userName,
        @RequestParam @ApiParam(value = "身份证号码", required = true) String idCard) {
        String authCodeOnServer = (String)CacheUtil.getCache().get(MSGCHKTYPE.REGISTER + account);
        if (!authCode.equals(authCodeOnServer)) {
            logger.warn(account + "=" + authCode + "-" + authCodeOnServer);
            throw new IllegalArgumentException("手机验证码错误");
        }

        List<TExpressman> result = service
                .queryList(InstanceUtil.newHashMap(new String[]{"account", "enable"}, new String[]{account, "1"}));
        if (result.size() >= 1) {
            throw new IllegalParameterException("手机号已注册.");
        } else {
            if (!IDCardUtil.isIdentity(idCard)) {
                throw new IllegalArgumentException("身份证号码错误");
            }
            TExpressman record = new TExpressman();
            record.setPhone(account);
            record.setPassword(SecurityUtil.encryptPassword(password));
            record.setUserName(userName);
            record.setIdCard(idCard);
            record.setOrderState(1);
            service.update(record);
        }
        return setSuccessModelMap();
    }

    @PostMapping("login.api")
    @ApiOperation(value = "骑手登录", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ModelMap> login(
        @RequestHeader("UUID") @ApiParam(value = "客户端生成的唯一ID", required = true) String uuid,
        @RequestHeader(required = false) @ApiParam("微信ID，暂不支持") String openId,
        @RequestHeader(required = false) @ApiParam("极光推送ID，暂不支持") String registrationId,
        @RequestParam @ApiParam(value = "手机号", required = true) String account,
        @RequestParam @ApiParam(value = "密码", required = true) String password) {
        Map<String, Object> params = InstanceUtil.newHashMap("enable", 1);
        params.put("account", account);
        List<TExpressman> expressmans = service.queryList(params);
        TExpressman expressman = expressmans.isEmpty() ? null : expressmans.get(0);

        if (expressman == null) {
            throw new LoginException("手机号或密码错误.");
        } else {
            if (SecurityUtil.encryptPassword(password).equals(expressman.getPassword())) {
                if (expressman.getRegistrationId() != null) {
                    if (registrationId != null && !registrationId.equals(expressman.getRegistrationId())) {
                        expressman.setRegistrationId(registrationId);
                        String content = "帐号[" + account + "]在别的设备登录";
                        HashMap<String, String> hashMap = new HashMap<String, String>();
                        hashMap.put("type", "3");
                        String equipment = expressman.getRegistrationId().substring(2, 3);
                        try {
                            if ("0".equals(equipment)) {
                                jpushHelper.sendNotificationAndroid("登录通知", content, hashMap,
                                    expressman.getRegistrationId());
                            } else {
                                jpushHelper.sendNotificationIOS("登录通知", content, hashMap,
                                    expressman.getRegistrationId());
                            }
                        } catch (Exception e) {
                            logger.info(ExceptionUtil.getStackTraceAsString(e));
                        }
                    }
                } else {
                    expressman.setRegistrationId(registrationId);
                }
                if (openId != null) {
                    expressman.setWxOpenId(openId);
                }
                expressman.setIsOnline(1);

                service.update(expressman);
                Token token = new Token();
                token.setTime(System.currentTimeMillis());
                token.setValue(expressman.getId().toString());
                CacheUtil.getCache().hset("S:iBase4J:EXPRESSMAN:TOKENS", uuid, JSON.toJSONString(token));
                expressman.setPassword(null);
                return setSuccessModelMap(expressman);
            } else {
                throw new LoginException("手机号或密码错误.");
            }
        }
    }

    @PostMapping("updatePwd.api")
    @ApiOperation(value = "修改密码", produces = MediaType.APPLICATION_JSON_VALUE, notes = "" + "接口需要以下五个参数：\n"
            + "1. UUID(header): 客户端生成的唯一ID，用作用户令牌，服务端用之识别用户，验证权限，每接口必传\n"
            + "2. sign: 请求参数的RSA签名(通过/app/secret.api获取RSA私钥)，用于防止请求参数被第三方拦截篡改，每接口必传。签名算法查看密钥接口\n"
            + "3. account: 用户名，目前只支持手机号\n" + "4. password: 密码\n" + "5. authCode: 手机短信验证码(通过/app/msg.api发送短信验证码)\n"
            + "注意：所有接口都需要传UUID和sign参数，UUID用作令牌，sign用作签名", response = TMember.class)
    public Object updatePwd(@RequestHeader("UUID") @ApiParam(value = "客户端生成的唯一ID", required = true) String uuid,
        @RequestParam @ApiParam(value = "手机号", required = true) String account,
        @RequestParam @ApiParam(value = "密码", required = true) String password,
        @RequestParam @ApiParam(value = "手机验证码", required = true) String authCode) throws Exception {
        String authCodeOnServer = (String)CacheUtil.getCache().get(MSGCHKTYPE.CHGPWD + account);
        if (!authCode.equals(authCodeOnServer)) {
            throw new IllegalArgumentException("手机验证码错误");
        }

        Map<String, Object> params = InstanceUtil.newHashMap("account", account);
        List<TExpressman> members = service.queryList(params);
        TExpressman member = members.isEmpty() ? null : members.get(0);

        if (member == null) {
            throw new IllegalArgumentException("手机号还没有注册.");
        } else {
            member.setPassword(SecurityUtil.encryptPassword(password));
            service.update(member);
            return setSuccessModelMap();
        }
    }

    @PostMapping("autoOrder.api")
    @ApiOperation(value = "自动派单", notes = "自动派单0手动1自动", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ModelMap> auto(HttpServletRequest request, Integer autoOrder) {
        Long expressmanId = ExpressmanHelper.getCurrent(request);
        TExpressman param = WebUtil.getParameter(request, TExpressman.class);
        TExpressman expressman = new TExpressman();
        expressman.setId(expressmanId);
        expressman.setAutoOrder(param.getAutoOrder());
        service.update(expressman);
        return setSuccessModelMap();
    }

    @PostMapping("orderState.api")
    @ApiOperation(value = "接单状态", notes = "接单状态0休息1接单", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ModelMap> orderState(HttpServletRequest request, Integer orderState) {
        Long expressmanId = ExpressmanHelper.getCurrent(request);
        TExpressman param = WebUtil.getParameter(request, TExpressman.class);
        TExpressman expressman = new TExpressman();
        expressman.setId(expressmanId);
        expressman.setOrderState(param.getOrderState());
        service.update(expressman);
        return setSuccessModelMap();
    }

    @PostMapping("sound.api")
    @ApiOperation(value = "新订单提醒声音", notes = "新订单提醒声音", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ModelMap> sound(HttpServletRequest request, String soundFile) {
        Long expressmanId = ExpressmanHelper.getCurrent(request);
        TExpressman param = WebUtil.getParameter(request, TExpressman.class);
        TExpressman expressman = new TExpressman();
        expressman.setId(expressmanId);
        expressman.setSoundFile(param.getSoundFile());
        service.update(expressman);
        return setSuccessModelMap();
    }

    @PostMapping("logout.api")
    @ApiOperation(value = "骑手登出", notes = "骑手登出，服务端进行相应处理", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<ModelMap> logout(HttpServletRequest request) {
        Long expressmanId = ExpressmanHelper.getCurrent(request);
        TExpressman expressman = WebUtil.getParameter(request, TExpressman.class);
        expressman.setId(expressmanId);
        expressman.setIsOnline(0);
        service.update(expressman);

        CacheUtil.getCache().hdel("EXPRESSMAN:TOKENS", request.getHeader("uuid"));

        return setSuccessModelMap();
    }
}
